'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ToastAndroid,
  Alert,
  BackAndroid
} from 'react-native';
import NavigationBar from 'react-native-navbar';

var _navigator ;
var _route;
class HttpView extends Component{

  componentWillMount(){
    _navigator = this.props.navigator;
    _route = this.props;
  }

  getByFetch() {
    fetch('https://m.baidu.com' )
    .then((response) => response.text())
    .then((responseText) => {
      ToastAndroid.show(responseText, ToastAndroid.SHORT);
      console.warn(new Date().getMilliseconds());
    })
    .catch((error) => {
      console.warn(error);
    }).done();
    console.warn('请求是异步的:'+new Date().getMilliseconds());
  }

  getByXMLHttpRequest() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = (e) => {
      if (request.readyState !== 4) {
        return;
      }
      if (request.status === 200) {
        ToastAndroid.show('success'+ request.responseText ,ToastAndroid.SHORT);
      } else {
        console.warn('error');
      }
    };
    request.open('GET', 'https://m.baidu.com');
    request.send();
  }

  postSource() {
    fetch('https://m.baidu.com' )
    .then((response) => response.text())
    .then((responseText) => {
      // Works on both iOS and Android
      Alert.alert(
        '请求结果',
        responseText.substring(0,100),
        [
          {text: 'Ask me later', onPress: () => console.warn('Ask me later pressed')},
          {text: 'Cancel', onPress: () => console.warn('Cancel Pressed'), style: 'cancel'},
          {text: 'OK', onPress: () => console.warn('OK Pressed')},
        ]
      )
    })
    .catch((error) => {
      console.warn(error);
    }).done();

  }

  render() {
    var id = _route.msg;
    const titleConfig = {
      title: '网络请求示例'
    };
    const leftConfig = {
      title:'返回',
      handler: function onNext() {
        _navigator.pop();
      }
    }
    return (
      <View style={{flex:1}}>
      <NavigationBar
      style={styles.common}
      leftButton={leftConfig}
      title={titleConfig} />
      <TouchableOpacity onPress={this.getByFetch} style={ styles.button }>
      <Text  >GET by fetch</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={this.getByXMLHttpRequest} style={ styles.button }>
      <Text >GET by XmlHttpRequest</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress= { this.postSource } style={ styles.button }>
      <Text >{id}</Text>
      </TouchableOpacity>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  button: {
    backgroundColor: '#e2e2e2',
    marginLeft: 20,
    marginRight: 20,
    marginTop: 10,
    alignSelf: 'stretch',
    alignItems: 'center',
    justifyContent: 'center',
    height:50
  },
  common:{
    marginLeft: 10,
    marginRight: 10,
  }
});
module.exports = HttpView;
